package com.yi.apipassenger.service;

import com.yi.internalcommon.constant.CommonStatusEnum;
import com.yi.internalcommon.constant.TokenConstants;
import com.yi.internalcommon.dto.ResponseResult;
import com.yi.internalcommon.dto.TokenResult;
import com.yi.internalcommon.responese.TokenResponse;
import com.yi.internalcommon.util.JwtUtils;
import com.yi.internalcommon.util.RedisPrefixUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public ResponseResult refreshToken(String refershTokenSrc) {
        //解析refreshToken
        TokenResult tokenResult = JwtUtils.checkToken(refershTokenSrc);

        if (tokenResult == null){
            return  ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }
        //读取redis中的refreshToken
        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();
        String referchTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstants.REFRESH_TOKEN_TYPE);
        String referchTokenRedis = stringRedisTemplate.opsForValue().get(referchTokenKey);
        //校验refreshToken
        if ((StringUtils.isBlank(referchTokenRedis))  || (!refershTokenSrc.trim().equals(referchTokenRedis.trim()))){
            return  ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }
        //生成双token
        String refershToken = JwtUtils.generatorToken(phone, identity, TokenConstants.REFRESH_TOKEN_TYPE);
        String accessToken = JwtUtils.generatorToken(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);

        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);

        stringRedisTemplate.opsForValue().set(accessTokenKey,accessToken,30, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(referchTokenKey,refershToken,31,TimeUnit.DAYS);

        TokenResponse  response=new TokenResponse();
        response.setAccessToken(accessToken);
        response.setRefreshToken(refershToken);

        return ResponseResult.success(response);
    }


}
